// WebSocket服务工具类
import { ref } from 'vue';
import { useAuctionStore } from '../stores/auction';
const auctionStore = useAuctionStore();

class WebSocketService {

    // Socket对象
    private socket: WebSocket | null = null;
    // 是否连接
    public isConnected = ref(false);

    constructor(private url: string) {
        this.connect();
    }

    // 创建websocket实例，监听socket事件
    private connect() {
        this.socket = new WebSocket(this.url);

        this.socket.onopen = () => {
            console.log('WS已连接');
            this.isConnected.value = true;
        };

        this.socket.onclose = () => {
            console.log('WS被关闭');
            this.isConnected.value = false;
        };

        this.socket.onerror = (error) => {
            console.error('WS出现错误:', error);
            this.isConnected.value = false;
        };
        this.socket.onmessage = (event: MessageEvent) => {
            // 判断返回消息（基于消息的路由）
            if (event.data == "auction") {
                auctionStore.upDateauctionHandleFlag(false);
                setTimeout(() => {
                    auctionStore.upDateauctionHandleFlag(true);
                }, 200)
                return;
            }
            if(event.data.startsWith('price')){
                console.log(event.data);
                //分隔，取出id和最新价格，存入pinia
                const mySplit = event.data.split(',');
                const subPrice = mySplit[0].substring(5);
                const subId = mySplit[1].substring(2);
                // 存入pinia的Map中
                auctionStore.setMyMap(subId, subPrice);
            }
        }
    }

    /**
     * 发送消息
     * @param message 消息
     */
    public send(message: string) {
        if (this.socket && this.isConnected.value) {
            this.socket.send(message);
        }
    }

    /**
     * 监听消息（弃用）
     * @returns 消息
     */
    public getMessage(): Promise<MessageEvent | null> {
        return new Promise((resolve) => {
            if (this.socket) {
                this.socket.onmessage = (event: MessageEvent) => {
                    if (event.data == "auction") {
                        console.log("有人竞拍·...");

                        auctionStore.upDateauctionHandleFlag(true);
                    }
                    resolve(event);
                };
            } else {
                resolve(null);
            }
        });
    }

    /**
     * 关闭WS连接
     */
    public close() {
        if (this.socket) {
            this.socket.close();
        }
    }
}

export default WebSocketService;
